<script setup lang="ts">
import { ref, reactive, onMounted, defineComponent } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUsers, updateUserStatus } from "@/api/index";
import LoadingSpinner from "@/components/common/LoadingSpinner.vue";
import EmptyState from "@/components/common/EmptyState.vue";

// 定义用户接口
interface User {
  id: string;
  username: string;
  email: string;
  phone: string;
  role: string;
  status: number;
  createTime: string;
  lastLoginTime?: string;
  avatar?: string;
}

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索参数
const searchForm = reactive({
  username: "",
  role: "",
  status: "",
});

// 用户列表
const userList = ref<User[]>([]);
const loading = ref(false);

// 用户角色选项
const roleOptions = [
  { value: "ADMIN", label: "管理员" },
  { value: "MERCHANT", label: "商家" },
  { value: "USER", label: "普通用户" },
  { value: "RIDER", label: "骑手" },
];

// 用户状态选项
const statusOptions = [
  { value: 1, label: "正常" },
  { value: 0, label: "禁用" },
];

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm,
    };

    console.log("正在请求用户数据，参数:", params);
    const res = await getUsers(params);
    console.log("API响应数据:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      userList.value = data.content || [];
      pagination.total = data.totalElements || 0;
      console.log("成功获取用户数据:", userList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      userList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请检查网络连接或API状态");
    userList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchUsers();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchUsers();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchUsers();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchUsers();
};

// 更改用户状态
const changeUserStatus = async (user: User) => {
  const newStatus = user.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? "启用" : "禁用";
  const apiStatus = newStatus === 1 ? "APPROVED" : "SUSPENDED";
  let reason = "";

  if (apiStatus === "SUSPENDED") {
    reason = "管理员禁用";
  }

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}用户 ${user.username} 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 根据API定义发送请求
    await updateUserStatus(user.id, apiStatus, reason);

    ElMessage.success(`${actionText}用户成功`);

    // 更新用户状态
    user.status = newStatus;
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${actionText}用户失败:`, error);
      ElMessage.error(`${actionText}用户失败，请重试`);
    }
  }
};

// 删除用户
const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？此操作不可恢复！`,
      "警告",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "error",
      }
    );

    // 这里应该调用删除用户的API
    ElMessage.success(`删除用户成功`);

    // 从列表中移除该用户
    userList.value = userList.value.filter((item) => item.id !== user.id);
  } catch (error) {
    if (error !== "cancel") {
      console.error(`删除用户失败:`, error);
      ElMessage.error(`删除用户失败，请重试`);
    }
  }
};

// 格式化时间
const formatDate = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取用户角色显示名称
const getRoleName = (role: string) => {
  const found = roleOptions.find((item) => item.value === role);
  return found ? found.label : role;
};

onMounted(() => {
  // 获取用户数据
  fetchUsers();
});

// 为组件定义名称
defineOptions({
  name: "UserManagement",
});
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            clearable
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template v-if="loading">
        <LoadingSpinner />
      </template>

      <template v-else>
        <el-table
          v-if="userList.length > 0"
          :data="userList"
          border
          style="width: 100%"
          row-key="id"
        >
          <el-table-column label="用户头像" width="80" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.username?.substring(0, 1).toUpperCase() }}
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" min-width="120" />

          <el-table-column prop="email" label="邮箱" min-width="180" />

          <el-table-column prop="phone" label="手机号" min-width="120" />

          <el-table-column prop="role" label="角色" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.role === 'ADMIN'
                    ? 'danger'
                    : row.role === 'MERCHANT'
                    ? 'warning'
                    : 'info'
                "
              >
                {{ getRoleName(row.role) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? "正常" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="注册时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="lastLoginTime"
            label="最后登录"
            min-width="160"
          >
            <template #default="{ row }">
              {{ row.lastLoginTime ? formatDate(row.lastLoginTime) : "未登录" }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="changeUserStatus(row)">
                {{ row.status === 1 ? "禁用" : "启用" }}
              </el-button>
              <el-button link type="danger" @click="deleteUser(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <EmptyState
          v-else
          text="暂无用户数据"
          description="当前没有符合条件的用户"
        />

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
